//
//  db_Downloading.m
//  AiliPlayer
//
//  Created by xy on 13-1-17.
//
//

#import "db_Downloading.h"
#import "sqlite3.h"

sqlite3 *database;

static  NSMutableArray *dblist;
@implementation db_Downloading

#pragma mark -
#pragma mark DownloadInfo
//打开数据库
+(void)openDataBase{
   // 2014elephant
	NSString *db = [[NSBundle mainBundle] pathForResource:@"51tour" ofType:@"db"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:DBPATH]) {
        [[NSFileManager defaultManager] copyItemAtPath:db toPath:DBPATH error:nil];
    }
   	int result=sqlite3_open([DBPATH UTF8String],&database);
	if(result!=SQLITE_OK){
		NSLog(@"open db failed");
	}else{
//        const char* key = [@"2014elephant" UTF8String];    //数据库文件加密
//        sqlite3_rekey(database, key, (int)strlen(key));      //数据库文件加密
        NSLog(@"\n===数据库打开or创建成功===\n");
    }
}

//关闭数据库
+(void)closeDatabase{
	sqlite3_close(database);
    NSLog(@"close db");
}

//获取所有
+(NSMutableArray*)searchAllDownloads{
    if (!dblist) {
        dblist = [NSMutableArray array];
        NSString *sql = @"select * from DOWNLOADING_INFO";
        sqlite3_stmt *stmt;
        sqlite3_prepare_v2(database, [sql UTF8String],-1,&stmt,nil);
        while (sqlite3_step(stmt)==SQLITE_ROW){
            char *name=(char*)sqlite3_column_text(stmt, 1);
            char *date=(char*)sqlite3_column_text(stmt, 2);
            char *progress=(char*)sqlite3_column_text(stmt, 3);
            char *bytes=(char*)sqlite3_column_text(stmt, 4);
//            char *finished=(char*)sqlite3_column_text(stmt, 5);
            char *url=(char*)sqlite3_column_text(stmt, 6);
            char *language=(char*)sqlite3_column_text(stmt, 7);
            ScenicScene *scenic = [[ScenicScene alloc] init];
            scenic.scenicName = [NSString stringWithUTF8String:name];
            scenic.progress = [[NSString stringWithUTF8String:progress] floatValue];
            scenic.zipSize = [[NSString stringWithUTF8String:bytes] floatValue];
            scenic.zipFile = [NSString stringWithUTF8String:url];
            scenic.isDownloading = NO;//[[NSString stringWithUTF8String:finished] boolValue];
            scenic.scenicId = [NSString stringWithUTF8String:date];
            scenic.language = [NSString stringWithUTF8String:language];
            
            [dblist addObject:scenic];
        }
    }
    return dblist;
}

+ (ScenicScene*)getScenic:(NSString*)scenicId language:(NSString*)language{
    for (ScenicScene *s in dblist) {
        if ([s.scenicId isEqualToString:scenicId]&&[s.language isEqualToString:language]) {
            return s;
        }
    }
    return nil;
}

//添加一条下载历史记录
+ (BOOL)addDownloadInfo:(ScenicScene *)downloadInfo
{
    if ([dblist containsObject:downloadInfo]) {
        return NO;
    }
    char *errormsg;
    NSString *insert=[NSString stringWithFormat:@"insert into DOWNLOADING_INFO (Name,ScenicId,Finished,Progress,Bytes,DownUrl,language) values ('%@','%@','%d','%f','%f','%@','%@')",downloadInfo.scenicName,downloadInfo.scenicId,downloadInfo.isDownloading,downloadInfo.progress,downloadInfo.zipSize,downloadInfo.zipFile,downloadInfo.language];
    int result=sqlite3_exec(database, [insert UTF8String],NULL,NULL,&errormsg);
    if(result!=SQLITE_OK){
        printf("%s",errormsg);
        NSLog(@"插入失败！");
        return NO;
    }
    [dblist addObject:downloadInfo];
    return YES;
}

+ (BOOL)updateDownloadInfo:(ScenicScene*)info{
    NSString *sql=[NSString stringWithFormat:@"update DOWNLOADING_INFO set Finished='%d',Progress='%f',Bytes='%f', DownUrl='%@' where ScenicId='%@' and language='%@'",info.isDownloading,info.progress,info.zipSize,info.zipFile,info.scenicId,info.language];

	int res=sqlite3_exec(database, [sql UTF8String], NULL, NULL, nil);
    if (res!=SQLITE_OK) {
        NSLog(@"更新失败！");
        return NO;
    }
    return YES;
}

//删除一条下载历史记录
+ (BOOL)deleteHistory:(ScenicScene *)downloadInfo{
    
    NSString *sql=[NSString stringWithFormat:@"delete from DOWNLOADING_INFO where ScenicId='%@' and language='%@'",downloadInfo.scenicId,downloadInfo.language];
    
	int res=sqlite3_exec(database, [sql UTF8String], NULL, NULL, nil);
	if (res!=SQLITE_OK) {
        NSLog(@"删除失败！");
        return NO;
    }
    if ([dblist containsObject:downloadInfo]) {
        [dblist removeObject:downloadInfo];
    }
    return YES;
}



//删除所有记录
+ (BOOL)deleteAllHistorys
{
	NSString *sql = @"delete from DOWNLOADING_INFO";
    
	int res=sqlite3_exec(database, [sql UTF8String], NULL, NULL, nil);
	if (res!=SQLITE_OK) {
        NSLog(@"删除失败！");
        return NO;
    }
	return YES;
}

//退出时调用
+(void)saveToDB{
    //重新写入未下完的数据到数据库
//    if ([[CommonData instance] downloadList].count!=0) {
//        for (QMTaskModel *model in [[CommonData instance] downloadList]) {
//            Song *info = [Tool changeTask:model];
//            [db_Downloading saveDownloadInfo:info];
//        }
//    }
}
@end
